/*
 * Copyright (c) Huawei Device Co., Ltd. 2023. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "channel_stub.h"
#include "common_utils.h"
#include "loghelper.h"
#include "message_parcel.h"
#include "se_common_exception.h"
#include "se_service_ipc_interface_code.h"

using namespace std;
namespace OHOS {
namespace SE {
namespace OMAPI {
int ChannelStub::OnRemoteRequest(uint32_t code,         /* [in] */
                                 MessageParcel &data,   /* [in] */
                                 MessageParcel &reply,  /* [out] */
                                 MessageOption &option) /* [in] */
    {
        DebugLog("ChannelStub::OnRemoteRequest occur, code is %{public}d", code);
        if (data.ReadInterfaceToken() != GetDescriptor()) {
            ErrorLog("ChannelStub OnRemoteRequest GetDescriptor failed");
            return ErrorCode::SE_IPC_TOKEN_ERROR;
        }
        switch (code) {
            case static_cast<uint32_t>(SeServiceIpcInterfaceCode::COMMAND_CHANNEL_CLOSE):
                return HandleClose(data, reply);
            case static_cast<uint32_t>(SeServiceIpcInterfaceCode::COMMAND_CHANNEL_IS_CLOSED):
                return HandleIsClosed(data, reply);
            case static_cast<uint32_t>(SeServiceIpcInterfaceCode::COMMAND_CHANNEL_IS_BASIC_CHANNEL):
                return HandleIsBasicChannel(data, reply);
            case static_cast<uint32_t>(SeServiceIpcInterfaceCode::COMMAND_CHANNEL_GET_SELECT_RESPONSE):
                return HandleGetSelectResponse(data, reply);
            case static_cast<uint32_t>(SeServiceIpcInterfaceCode::COMMAND_CHANNEL_TRANSMIT):
                return HandleTransmit(data, reply);
            case static_cast<uint32_t>(SeServiceIpcInterfaceCode::COMMAND_CHANNEL_SELECT_NEXT):
                return HandleSelectNext(data, reply);
            default:
                return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
    }
}
int ChannelStub::HandleClose(OHOS::MessageParcel& data, OHOS::MessageParcel& reply)
{
    int statusCode = Close();
    reply.WriteInt32(statusCode);
    return ERR_NONE;
}

int ChannelStub::HandleIsClosed(OHOS::MessageParcel& data, OHOS::MessageParcel& reply)
{
    bool isClosed = true;
    int statusCode = IsClosed(isClosed);
    reply.WriteBool(isClosed);
    reply.WriteInt32(statusCode);
    return ERR_NONE;
}

int ChannelStub::HandleIsBasicChannel(OHOS::MessageParcel& data, OHOS::MessageParcel& reply)
{
    bool isBasicChannel = false;
    int statusCode = IsBasicChannel(isBasicChannel);
    reply.WriteBool(isBasicChannel);
    reply.WriteInt32(statusCode);
    return ERR_NONE;
}

int ChannelStub::HandleGetSelectResponse(OHOS::MessageParcel& data, OHOS::MessageParcel& reply)
{
    std::string response;
    int statusCode = GetSelectResponse(response);
    reply.WriteString(response);
    reply.WriteInt32(statusCode);
    return ERR_NONE;
}

int ChannelStub::HandleTransmit(OHOS::MessageParcel& data, OHOS::MessageParcel& reply)
{
    std::string command = data.ReadString();
    std::string response;
    int32_t status = ErrorCode::SE_SUCCESS;
    try {
        status = Transmit(command, response);
    } catch (const AccessControlError& e) {
        ErrorLog("HandleTransmit failed: AccessControlError");
        status = ErrorCode::SE_ACCESS_CONTROL_ERROR;
    } catch (const IllegalStateError& e) {
        ErrorLog("HandleTransmit failed: IllegalStateError");
        status = ErrorCode::SE_ILLEGAL_STATE_ERROR;
    } catch (const UnsupportedOperationError& e) {
        ErrorLog("HandleTransmit failed: UnsupportedOperationError[%{public}s]", e.response_.c_str());
        if (response.empty() && !e.response_.empty()) {
            response = e.response_;
        }
        // modify status to success for JS interface don't throw exception, so business can catch response as before.
        status = ErrorCode::SE_SUCCESS;
    } catch (const IllegalArgumentError& e) {
        ErrorLog("HandleTransmit failed: IllegalArgumentError");
        status = ErrorCode::SE_ILLEGAL_PARAMETER_ERROR;
    } catch (const IllegalReferenceError& e) {
        ErrorLog("HandleTransmit failed: IllegalReferenceError");
        status = ErrorCode::SE_ILLEGAL_REFERENCE_ERROR;
    } catch (const NoSuchElementError& e) {
        ErrorLog("HandleTransmit failed: NoSuchElementError[%{public}s]", e.response_.c_str());
        if (response.empty() && !e.response_.empty()) {
            response = e.response_;
        }
        // modify status to success for JS interface don't throw exception, so business can catch response as before.
        status = ErrorCode::SE_SUCCESS;
    } catch (const ChannelNotAvailableError& e) {
        ErrorLog("HandleTransmit failed: ChannelNotAvailableError");
        status = ErrorCode::SE_CHANNEL_NOT_AVAILABLE_ERROR;
    } catch (const SecurityError& e) {
        ErrorLog("HandleTransmit failed: IOError");
        status = ErrorCode::SE_IO_ERROR;
    } catch (const IOError& e) {
        ErrorLog("HandleTransmit failed: IOError");
        status = ErrorCode::SE_IO_ERROR;
    } catch (const GeneralError& e) {
        ErrorLog("HandleTransmit failed: GeneralError");
        status = ErrorCode::SE_GENERAL_ERROR;
    } catch (const NullPointerError& e) {
        ErrorLog("HandleTransmit failed: NullPointerError");
        status = ErrorCode::SE_GENERAL_ERROR;
    }
    reply.WriteString(response);
    reply.WriteInt32(status);
    return ERR_NONE;
}

int ChannelStub::HandleSelectNext(OHOS::MessageParcel& data, OHOS::MessageParcel& reply)
{
    bool selectStatus;
    int statusCode = SelectNext(selectStatus);
    reply.WriteBool(selectStatus);
    reply.WriteInt32(statusCode);
    return ERR_NONE;
}
}  // namespace OMAPI
}  // namespace SE
}  // namespace OHOS